/**
*┌──────────────────────────────────────────────────────────────┐
*│　描    述：服务                                                   
*│　作    者：sys                                              
*│　创建时间：2020-12-02 14:55:26   
*│　说    明：代码生成器生成   
*└──────────────────────────────────────────────────────────────┘
*/
using AutoMapper;
using SXFramWork.Core;
using SXFramWork.Model;
using SXFramWork.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SXFramWork.Service
{
    /// <summary>
	/// SysRole服务层
	/// </summary>
    public class SysRoleService: ISysRoleService
    {
        private readonly ISysRoleRepository _repository;
        private readonly ISysUserRoleRepository _userRoleRepository;
        private readonly IMapper _mapper;
        public SysRoleService(ISysRoleRepository repository,IMapper mapper,ISysUserRoleRepository sysUserRoleRepository)
        {
            _userRoleRepository = sysUserRoleRepository;
            _mapper = mapper;
            _repository = repository;
        }

        public async Task<IApiResult> Add(RoleAddModel model)
        {
            var entity = _mapper.Map<SysRoleEntity>(model);
            var id = GuidHelper.NewSequentialGuid(SequentialGuidType.SequentialAtEnd);
            entity.Id = id;
            entity.CreateTime = DateTime.Now;
            var res= await _repository.InsertAsync(entity);
            if (res.IsNull())
                return ApiResult.NotOk("新增角色失败");
            return ApiResult.Ok(res);
        }

        public async Task<IApiResult> Delete(List<string> ids)
        {
            //var idArr = ids.Split(',').ToList();
            //判断该角色是否被绑定
            var flag=await _userRoleRepository.ExistsRolesAsync(ids);
            if (flag)
            {
                return ApiResult.NotOk("删除角色失败，角色被用户绑定");
            }
            var res = await _repository.DeleteManyAsync(ids, "sysrole");
            if (res <= 0)
                return ApiResult.NotOk("删除角色失败");

            return ApiResult.Ok("","成功删除" + res + "条数据");          
        }

        public async Task<IApiResult> GetById(string id)
        {
            var res = await _repository.GetAsync(id);
            return ApiResult.Ok(res);
        }

        public async Task<IApiResult> Query(RoleQueryModel model)
        {
            var result = new PageResult<SysRoleEntity>
            {
                Rows = await _repository.Query(model),
                TotalCount = model.TotalCount
            };
            return ApiResult.Ok(result);
        }

        public async Task<IApiResult> Update(RoleUpdateModel model)
        {
            var entity = _mapper.Map<SysRoleEntity>(model);
            var res = await _repository.UpdateAsync(entity);
            if (!res)
                return ApiResult.NotOk("修改角色失败");
            return ApiResult.Ok("修改成功");
        }
    }
}